<?php

class Image extends CActiveRecord
{
    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }

	public function rules()
	{
		return array(
			array('image_id, image_path, image_x, image_y, alt', 'safe'),
		);
	}

    public function tableName()
    {
        return '{{images}}';
    }

	public function relations()
	{
		return array(
		);
	}

	public static function getUploadBasePath($object_type = 'product')
	{
		return Yii::getPathOfAlias('file') . "/$object_type/";
	}

	public static function getUploadPath($object_type = 'product')
	{
		$path =  self::getUploadBasePath($object_type) . date('Y/m/d');

		if ( !file_exists($path) ) mkdir ($path, 0777, true);

		return $path;
	}

	public static function attachImagePair($name, $object_type, $object_id) {
		$pairs_data = getPost($name.'_image_data');
		$upload_base_path = self::getUploadBasePath($object_type);
		$upload_path = self::getUploadPath($object_type);

		if ( !empty($pairs_data) ) {
			foreach ($pairs_data as $k => $p_data) {
				$field_name = "file_{$name}_image_icon[$k]";
				$image_hndl = CUploadedFile::getInstanceByName($field_name);
				$image = new Image;
				
				if ( $image_hndl != null ) {
					// save new image
					$image_file = $upload_path . '/' . $image_hndl->name;
					$image_path = str_replace($upload_base_path, '', $image_file);
					$image_hndl->saveAs($image_file);
					list($w, $h, $t, $a) = @getimagesize($image_file);

					$image->isNewRecord = true;
					$image->image_id = null;
					$image->image_path = $image_path;
					$image->image_x = $w;
					$image->image_y = $h;
					$image->alt = $p_data['image_alt'];
					if ( !$image->save() ) {
						return false;
					}
				}

				if ( empty($p_data['pair_id']) ) {
					$imageLinkModel = new ImageLink;
				} else {
					$imageLinkModel = ImageLink::model()->findByPk($p_data['pair_id']);
				}

				$imageLinkModel->attributes = $p_data;
				$imageLinkModel->object_type = $object_type;
				$imageLinkModel->object_id = $object_id;
				if ( $image->image_id ) {
					$imageLinkModel->image_id = $image->image_id;
					$imageLinkModel->save();
				} elseif ( $imageLinkModel->image_id ) {
					$imageLinkModel->save();
				}
			}
		}
	}
}
?>